

local string_utils = require("mvc.utils.string_utils");


--[[
	获取uri最后一段
	uri:/abc/def/ghi 返回ghi
]]
local function get_method(uri)
	--[[
	local b = string.find(uri, "?");
	local e = #uri;
	if b ~= nil then
		e = b - 1
	end
	uri = string.sub(uri, 1, e);
	]]
	local array = string_utils.split(uri, "/");
	return array[#array];
end


--[[
	判断uri是否与pattern匹配
	pattern:/*/*/a      uri:/abc/def/a   true
	pattern:/abc/*/a      uri:/abc/def/a   true
	pattern:/*/def/a      uri:/abc/def/a   true
	pattern:/abc/**      uri:/abc/def true
	pattern:/abc/**      uri:/abc/def/afas true
	
	pattern:/*/*/b      uri:/abc/def/a   false
	pattern:/def/*/a      uri:/abc/def/a   false
	pattern:/*/abc/a      uri:/abc/def/a   false
	pattern:/*/a      uri:/abc/def/a   false
	
	@uri
	@pattern
]]
local function uri_pattern_match(uri, pattern)
	local is_match = true;
	local uri_a = string_utils.split(uri, "/");
	local pattern_a = string_utils.split(pattern, "/");
	
	--[[
	if #uri_a ~= #pattern_a then
		return false;
	end
	]]
	
	local u_item = nil;
	local p_item = nil;
	local jl = #pattern_a;
	
	for i = 1, #uri_a, 1 do
		u_item = uri_a[i];
		if (i > jl) then --前缀匹配
			p_item = pattern_a[jl];
			is_match = is_match and (p_item == "**");
		else --全路径匹配
			p_item = pattern_a[i];
			is_match = is_match and (p_item == "*" or u_item == p_item);
		end
	end
	
	return is_match;
end

local _M = {  
   get_method = get_method,
   uri_pattern_match = uri_pattern_match
}

return _M